'use strict';
const moment = require('moment');
const AlipaySdk = require('alipay-sdk').default;
const Controller = require('egg').Controller;
const AlipayFormData = require('alipay-sdk/lib/form').default;
const formData = new AlipayFormData();

class PayController extends Controller {
  async show() {
    const { ctx, service } = this;
    const { data: { _id: uid } } = ctx.state.user;
    const res = await service.cart.getOrderResult(ctx.params.id, uid);
    ctx.body = {
      result: res,
    };
  }
  async create() {
    const alipaySdk = new AlipaySdk({
      appId: this.config.alipay.appId,
      privateKey: this.config.alipay.privateKey,
      alipayPublicKey: this.config.alipay.alipayPublicKey,
      dev: true,
    });
    const { ctx, service } = this;
    const { body } = ctx.request;
    const { data: { _id: uid } } = ctx.state.user;
    const time = moment().format('YYYYMMDDHHmmss');
    const orderId = time + uid;
    const { amount, code } = await service.class.getTotalAmount(body.cart, uid);
    if (body.cart.length === 0) {
      ctx.status = 400;
      ctx.body = {
        code: '4002',
        msg: '购物车中无内容',
      };
      return;
    }
    if (code === 1) { // 订单中存在已购买的商品
      ctx.status = 400;
      ctx.body = {
        code: '40001',
        msg: '购物车中存在已购商品，订单创建失败',
      };
      return;
    }
    service.cart.orderCreate(body.cart, orderId, amount, uid);
    formData.addField('bizContent', {
      outTradeNo: orderId,
      subject: '卓异教育订单',
      totalAmount: amount,
      sellerId: this.config.seller_id,
      quit_url: `http://localhost:8000/#/result/${orderId}`,
    });
    const res = await alipaySdk.exec('alipay.trade.wap.pay',
      {},
      {
        formData,
      }
    );
    console.log(res);
    ctx.body = res;
  }
}

module.exports = PayController;
